package com.imc.api.order.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imc.api.attence.dao.repository.LessonRepository;
import com.imc.api.attence.pojo.Lesson;
import com.imc.api.order.dao.IOrderMapper;
import com.imc.api.order.pojo.OrderDetail;
import com.imc.api.order.pojo.OrderDetailSchedule;
import com.imc.api.order.pojo.UserOrgAccount;
import com.imc.api.order.repository.IOrderDetailScheduleRepository;
import com.imc.api.order.repository.IUserOrgAccountRepository;
import com.imc.api.order.repository.IWxMpOrderRepository;
import com.imc.api.order.pojo.Order;
import com.imc.api.order.repository.IWxOrderDetailRepository;
import com.imc.api.order.tuple.ConfirmOrder;
import com.imc.api.order.tuple.RowData;
import com.imc.api.shopmall.dao.ShopMallMapper;
import com.imc.api.shopmall.dao.ShopMallRepository;
import com.imc.api.shopmall.pojo.ShopMall;
import com.imc.core.config.feign.MyPageImpl;
import com.imc.core.utils.DateUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.core.utils.NumberFormat;
import com.imc.platform.base.user.dao.repository.UserRepository;
import com.imc.platform.base.user.pojo.User;
import com.imc.platform.base.user.pojo.UserCountLog;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/*
 * 类描述：微信订单服务类
 * 开发者：tanweiping
 * 创建日期：2018/10/28 21:31
 */
@Service
@Transactional
@Slf4j
public class WxOrderService {

    @Autowired
    UserRepository userRepository;//用户操作仓库

    @Autowired
    ShopMallRepository shopMallRepository;//商城mall操作仓库

    @Autowired
    IWxMpOrderRepository iWxMpOrderRepository;//微信订单操作仓库

    @Autowired
    IWxOrderDetailRepository iWxOrderDetailRepository;//微信订单详情操作仓库

    @Autowired
    MysqlUtil mysqlUtil;//数据库操作类

    @Autowired
    ShopMallMapper shopMallMapper;//商城mall mapper

    @Autowired
    IOrderMapper iOrderMapper;//订单mapper

    @Autowired
    IUserOrgAccountRepository userOrgAccountRepository;

    @Autowired
    IOrderDetailScheduleRepository iOrderDetailScheduleRepository;

    @Autowired
    LessonRepository lessonRepository;

    /*
     * tanweiping  2018/9/25 19:59
     * 方法描述：获取订单
     */
    public MyPageImpl getOrderList(Principal principal, Pageable pageable, String status_,String option) {
        Integer status = null;
        switch (status_) {
            case "all":
                status = null;
                break;
            case "topay":
                status = 1;
                break;
            case "sign":
                status = 2;
                break;
        }

        User user = userRepository.findAllByLoginName(principal.getName());
//        Page <Order> orders = status.equals("all") ?
//                iWxMpOrderRepository.findAllByUserIdAndTradeNoNotNull(String.valueOf(user.getId()), pageable) :
//                iWxMpOrderRepository.findAllByUserIdAndStatusAndTradeNoNotNull(String.valueOf(user.getId()), status_, pageable);

        /*
         * goodsList
         */
        PageHelper.startPage(pageable.getPageNumber()+1,pageable.getPageSize());

        Map<String,Object> params = new HashMap<>();
        params.put("userId",user.getId());
        params.put("status",status);
        params.put("status_",status_);
        params.put("currentDate",DateUtils.getCurrentDateDD());
//        if(!StringUtils.isEmpty(option)){
//            params.put("option",option);
//        }
        List <Map<String,Object>> orderList = iOrderMapper.queryMyLessonList(params);
        PageInfo info = new PageInfo <>(orderList);


        List <Map <String, Object>> resp = new ArrayList <>();
        if (info.getSize()>0) {
            orderList
                    .forEach(
                            order -> {
                                String orderStatus = String.valueOf(order.getOrDefault("status","0"));
                                order.put("statusLabel",Order.getStatusLabel(orderStatus));
                                order.put("orderAmount", NumberFormat.formatToNumber(new BigDecimal(String.valueOf(order.getOrDefault("orderAmount","0")))));
                                val goodsList = iOrderMapper.findAllByOrderId(Integer.parseInt(String.valueOf(order.get("id"))));
                                if (!goodsList.isEmpty()){
                                    /*
                                    获取课程里用户选择的课时
                                     */
//                                    goodsList.forEach(
//                                            goods->{
//                                                //detailId
//                                                String detailId = String.valueOf(goods.get("detailId"));
//                                                List<Map<String,Object>> scheduleList = iOrderMapper.queryMyLessonSchduleList(detailId);
//                                                if(!scheduleList.isEmpty()){
//                                                    goods.put("scheduleList",scheduleList);
//                                                }
//                                            }
//                                    );
                                    order.put("goodsList", goodsList);
                                }
                                resp.add(
                                        order
                                );
                            }
                    );
        }

        return new MyPageImpl(resp, info.isIsLastPage());
    }

    /*
    课时结算下单
     */
    public void postOrder(User user,Lesson lesson,int num,List<String> scheduleIdList,UserOrgAccount userOrgAccount,String userSubId,String loginName){
        int current = userOrgAccount.getLessonAccount().intValue();
        int take = num*scheduleIdList.size();

        String tradeNo = String.valueOf(new Date().getTime());
        /*
        创建订单
         */
        Order order = Order
                .builder()
                .userId(String.valueOf(user.getId()))
                .userSubId(userSubId)
                .orderDate(DateUtils.getCurrentDate())
                .status(2)
                .tradeNo(tradeNo)
                .tradeType("taoliAccount")
                .orderTakeClassTime(take)
                .build();

        Order order_ = iWxMpOrderRepository.save(order);

        OrderDetail orderDetail = OrderDetail
                .builder()
                .orderId(order_.getId())
                .goodsId(String.valueOf(lesson.getId()))
                .quantity(num)
                .status(2)
                .takeClassTime(take)
                .build();

        OrderDetail orderDetail_ = iWxOrderDetailRepository.save(orderDetail);

        if (scheduleIdList!=null) {
            List<OrderDetailSchedule> orderDetailScheduleList = scheduleIdList.stream()
                    .map(
                            s -> OrderDetailSchedule.builder().orderdetailId(String.valueOf(orderDetail_.getId())).scheduleId(s).build()
                    ).collect(Collectors.toList());

            iOrderDetailScheduleRepository.save(orderDetailScheduleList);
        }

        userOrgAccount.setLessonAccount(current-take);
        /*
        更新课时存储
         */
        userOrgAccountRepository.save(userOrgAccount);
        log.info("用户还剩课时数："+userOrgAccount.getLessonAccount());
        UserCountLog.builder()
                .userCountId(userOrgAccount.getId())
                .userId(user.getId())
                .result("新增成功")
                .userLoginName(loginName)
                .originalNum(0)
                .newNum(userOrgAccount.getLessonAccount())
                .createTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                .remarks("小程序端充值")
                .build();
        lesson.setStock(lesson.getStock()-num);

        lessonRepository.save(lesson);

    }

    /*
     * YT  2018/10/28 21:33
     * 方法描述：立即下单
     */
    public ConfirmOrder postOrder(User user, Lesson lesson,int num,List<String> scheduleIdList,String userSubId) throws Exception {


        int size = scheduleIdList==null?Integer.parseInt(lesson.getLessonDate()):scheduleIdList.size();

        BigDecimal price = new BigDecimal(lesson.getGroupPrice())
                .multiply(
                        new BigDecimal(num*size)
                                .divide(new BigDecimal(lesson.getLessonDate())));

        Order order = Order
                .builder()
                .userSubId(userSubId)
                .userId(String.valueOf(user.getId()))
                .orderDate(DateUtils.getCurrentDate())
                .status(0)
                .orderAmount(price)
                .build();

        Order order_ = iWxMpOrderRepository.save(order);

        OrderDetail orderDetail = OrderDetail
                .builder()
                .orderId(order_.getId())
                .goodsId(String.valueOf(lesson.getId()))
                .quantity(num)
                .status(0)
                .price(price)
                .amounts(price)
                .build();

        OrderDetail orderDetail_ = iWxOrderDetailRepository.save(orderDetail);
        if (scheduleIdList!=null){
            List<OrderDetailSchedule> orderDetailScheduleList = scheduleIdList.stream()
                    .map(
                            s->OrderDetailSchedule.builder().orderdetailId(String.valueOf(orderDetail_.getId())).scheduleId(s).build()
                    ).collect(Collectors.toList());

            iOrderDetailScheduleRepository.save(orderDetailScheduleList);
        }

        lesson.setStock(lesson.getStock()-num);

        lessonRepository.save(lesson);

        ConfirmOrder confirmOrder = ConfirmOrder.builder().build();
        confirmOrder.setOrder(order_);
        confirmOrder.setOrderId(order_.getId());
        confirmOrder.setTotalFee(price.toString());
        confirmOrder.setOrderId(order_.getId());
        confirmOrder.setGoodsList(new ArrayList() {{
            add(lesson);
        }});
        return confirmOrder;

    }

    /*
     * YT  2018/10/28 21:34
     * 方法描述：
     */
    public ConfirmOrder prepayForMall(Principal principal, List <Integer> ids) throws Exception {
        User user = userRepository.findAllByLoginName(principal.getName());

        String date = DateUtils.getCurrentDate();
        List <ShopMall> shopMallList = shopMallRepository.findAllByUserIdAndIdIn(String.valueOf(user.getId()), ids);

        List <String> goodsIds = shopMallList.stream().map(s -> s.getSkuId()).collect(Collectors.toList());
        /*
        判断此人是否存在此商品订单，是，则抛出异常
         */
//        int size = iWxMpOrderRepository.queryCountForSku(goodsIds,user.getId());
//        if (size>0){
//            throw new Exception("已经存在该课程的订单");
//        }

        BigDecimal orderAmount = shopMallList.stream()
                .map(s -> s.getPrice().multiply(new BigDecimal(s.getNum())))
                .reduce((a, b) -> a.add(b)).get();

        Order order = Order.builder().userId(String.valueOf(user.getId())).orderDate(date).status(0).orderAmount(orderAmount).build();

        Order order_ = iWxMpOrderRepository.save(order);

        List <OrderDetail> orderDetailList = new ArrayList <>();

        shopMallList.forEach(
                shopMall -> {
                    orderDetailList.add(
                            OrderDetail
                                    .builder()
                                    .orderId(order_.getId())
                                    .goodsId(shopMall.getSkuId())
                                    .quantity(shopMall.getNum())
                                    .status(0)
                                    .price(shopMall.getPrice())
                                    .amounts(shopMall.getPrice().multiply(new BigDecimal(shopMall.getNum())))
                                    .build()
                    );
                }
        );
        iWxOrderDetailRepository.save(orderDetailList);

        ConfirmOrder confirmOrder = ConfirmOrder.builder().build();

        List <RowData> rowDataList = new ArrayList <RowData>() {{
            add(RowData.builder().label("原价").value(orderAmount.toString()).valueKey("oldPrice").build());
            add(RowData.builder().label("优惠").value("0").valueKey("delPrice").build());
            add(RowData.builder().label("实付").value(orderAmount.toString()).valueKey("truePrice").build());
        }};
        //confirmOrder.setRowDataList(rowDataList);

        confirmOrder.setOrderId(order_.getId());

        confirmOrder.setTotalFee(orderAmount.toString());

        String skuIds = shopMallList.stream().map(s -> s.getSkuId()).reduce((s, s1) -> s.concat(",").concat(s1)).get();

        List <Lesson> lessonList = shopMallMapper.queryLessonList(skuIds);

//        lessonList.forEach(
//                lesson -> lesson.setNum(
//                        shopMallList.stream().filter(s -> s.getSkuId().equals(lesson.getId())).findFirst().get().getNum()
//                )
//        );
//
//        confirmOrder.setGoodsList(lessonList);

        return confirmOrder;
    }

    /*
     * YT  2018/10/28 21:34
     * 方法描述：保存订单
     */
    public Order save(Order order) {
        return iWxMpOrderRepository.save(order);
    }


    public List<String> getAvailableSchedule(String orderDetailId){
        List<String> available = iOrderMapper.getAvailableSchedule(orderDetailId);
        return available;
    }

}
